{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">完整项目地址：https://github.com/bat67/Deep-Learning-with-PyTorch-A-60-Minute-Blitz-cn ， 嘤嘤嘤求star~，最新版也会首先更新在github上,有误的地方拜托大家指出~"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Autograd：自动求导"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "PyTorch中，所有神经网络的核心是`autograd`包。先简单介绍一下这个包，然后训练我们的第一个的神经网络。\n",
    "\n",
    "`autograd`包为张量上的所有操作提供了自动求导机制。它是一个在运行时定义（define-by-run）的框架，这意味着反向传播是根据代码如何运行来决定的，并且每次迭代可以是不同的.\n",
    "\n",
    "让我们用一些简单的例子来看看吧。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1 张量"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`torch.Tensor`是这个包的核心类。如果设置它的属性 `.requires_grad`为`True`，那么它将会追踪对于该张量的所有操作。当完成计算后可以通过调用`.backward()`，来自动计算所有的梯度。这个张量的所有梯度将会自动累加到`.grad`属性.\n",
    "\n",
    "要阻止一个张量被跟踪历史，可以调用`.detach()`方法将其与计算历史分离，并阻止它未来的计算记录被跟踪。\n",
    "\n",
    "为了防止跟踪历史记录（和使用内存），可以将代码块包装在`with torch.no_grad():`中。在评估模型时特别有用，因为模型可能具有`requires_grad = True`的可训练的参数，但是我们不需要在此过程中对他们进行梯度计算。\n",
    "\n",
    "还有一个类对于autograd的实现非常重要：`Function`。\n",
    "\n",
    "`Tensor`和`Function`互相连接生成了一个非循环图，它编码了完整的计算历史。每个张量都有一个`.grad_fn`属性，它引用了一个创建了这个`Tensor`的`Function`（除非这个张量是用户手动创建的，即这个张量的`grad_fn`是`None`）。\n",
    "\n",
    "如果需要计算导数，可以在`Tensor`上调用`.backward()`。如果`Tensor`是一个标量（即它包含一个元素的数据），则不需要为`backward()`指定任何参数，但是如果它有更多的元素，则需要指定一个`gradient`参数，它是形状匹配的张量。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "创建一个张量并设置`requires_grad=True`用来追踪其计算历史"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[1., 1.],\n",
      "        [1., 1.]], requires_grad=True)\n"
     ]
    }
   ],
   "source": [
    "x = torch.ones(2, 2, requires_grad=True)\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对这个张量做一次运算："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[3., 3.],\n",
      "        [3., 3.]], grad_fn=<AddBackward0>)\n"
     ]
    }
   ],
   "source": [
    "y = x + 2\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`y`是计算的结果，所以它有`grad_fn`属性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<AddBackward0 object at 0x0000024C015A71D0>\n"
     ]
    }
   ],
   "source": [
    "print(y.grad_fn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对y进行更多操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[27., 27.],\n",
      "        [27., 27.]], grad_fn=<MulBackward0>) tensor(27., grad_fn=<MeanBackward1>)\n"
     ]
    }
   ],
   "source": [
    "z = y * y * 3\n",
    "out = z.mean()\n",
    "\n",
    "print(z, out)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`.requires_grad_(...)` 原地改变了现有张量的 `requires_grad` 标志。如果没有指定的话，默认输入的这个标志是`False`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "<SumBackward0 object at 0x0000024C03915978>\n"
     ]
    }
   ],
   "source": [
    "a = torch.randn(2, 2)\n",
    "a = ((a * 3) / (a - 1))\n",
    "print(a.requires_grad)\n",
    "a.requires_grad_(True)\n",
    "print(a.requires_grad)\n",
    "b = (a * a).sum()\n",
    "print(b.grad_fn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2 梯度"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因为`out`是一个标量。所以让我们直接进行反向传播，`out.backward()`和`out.backward(torch.tensor(1.))`等价"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "out.backward()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输出导数`d(out)/dx`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[4.5000, 4.5000],\n",
      "        [4.5000, 4.5000]])\n"
     ]
    }
   ],
   "source": [
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "得到都是`4.5`的矩阵。调用`out`张量 $“o”$。\n",
    "\n",
    "得到 \n",
    "\n",
    "$$o = \\frac{1}{4}\\sum_i z_i$$\n",
    "\n",
    "$$z_i = 3(x_i+2)^2$$\n",
    "\n",
    "和\n",
    "\n",
    "$$z_i\\bigr\\rvert_{x_i=1} = 27$$\n",
    "\n",
    "因此,\n",
    "\n",
    "$$\\frac{\\partial o}{\\partial x_i} = \\frac{3}{2}(x_i+2)$$\n",
    "\n",
    "所以，\n",
    "\n",
    "$$\\frac{\\partial o}{\\partial x_i}\\bigr\\rvert_{x_i=1} = \\frac{9}{2} = 4.5$$\n",
    "\n",
    "数学上，若有向量值函数 $\\vec{y}=f(\\vec{x})$，那么 $\\vec{y}$ 相对于 $\\vec{x}$ 的梯度是一个雅可比矩阵：\n",
    "\n",
    "$$\n",
    "J=\\left(\\begin{array}{ccc}\n",
    "   \\frac{\\partial y_{1}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{1}}\\\\\n",
    "   \\vdots & \\ddots & \\vdots\\\\\n",
    "   \\frac{\\partial y_{1}}{\\partial x_{n}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{n}}\n",
    "   \\end{array}\\right)\n",
    "$$\n",
    "\n",
    "通常来说，`torch.autograd` 是计算雅可比向量积的一个“引擎”。也就是说，给定任意向量 $v=\\left(\\begin{array}{cccc} v_{1} & v_{2} & \\cdots & v_{m}\\end{array}\\right)^{T}$，计算乘积 $J\\cdot v$。如果 $v$ 恰好是一个标量函数 $l=g\\left(\\vec{y}\\right)$ 的导数，即 $v=\\left(\\begin{array}{ccc}\\frac{\\partial l}{\\partial y_{1}} & \\cdots & \\frac{\\partial l}{\\partial y_{m}}\\end{array}\\right)^{T}$，那么根据链式法则，雅可比向量积应该是 $l$ 对 $\\vec{x}$ 的导数：\n",
    "\n",
    "$$\n",
    "J\\cdot v=\\left(\\begin{array}{ccc}\n",
    "   \\frac{\\partial y_{1}}{\\partial x_{1}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{1}}\\\\\n",
    "   \\vdots & \\ddots & \\vdots\\\\\n",
    "   \\frac{\\partial y_{1}}{\\partial x_{n}} & \\cdots & \\frac{\\partial y_{m}}{\\partial x_{n}}\n",
    "   \\end{array}\\right)\\left(\\begin{array}{c}\n",
    "   \\frac{\\partial l}{\\partial y_{1}}\\\\\n",
    "   \\vdots\\\\\n",
    "   \\frac{\\partial l}{\\partial y_{m}}\n",
    "   \\end{array}\\right)=\\left(\\begin{array}{c}\n",
    "   \\frac{\\partial l}{\\partial x_{1}}\\\\\n",
    "   \\vdots\\\\\n",
    "   \\frac{\\partial l}{\\partial x_{n}}\n",
    "   \\end{array}\\right)\n",
    "$$\n",
    "\n",
    "雅可比向量积的这一特性使得将外部梯度输入到具有非标量输出的模型中变得非常方便。\n",
    "\n",
    "现在我们来看一个雅可比向量积的例子:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([-898.3647, -192.8532, 1164.7910], grad_fn=<MulBackward0>)\n"
     ]
    }
   ],
   "source": [
    "x = torch.randn(3, requires_grad=True)\n",
    "\n",
    "y = x * 2\n",
    "while y.data.norm() < 1000:\n",
    "    y = y * 2\n",
    "\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这种情况下，`y`不再是标量。`torch.autograd`不能直接计算完整的雅可比矩阵，但是如果我们只想要雅可比向量积，只需将这个向量作为参数传给`backward`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([1.0240e+02, 1.0240e+03, 1.0240e-01])\n"
     ]
    }
   ],
   "source": [
    "v = torch.tensor([0.1, 1.0, 0.0001], dtype=torch.float)\n",
    "y.backward(v)\n",
    "\n",
    "print(x.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了防止跟踪历史记录（和使用内存），可以将代码块包装在`with torch.no_grad():`中。在评估模型时特别有用，因为模型可能具有`requires_grad = True`的可训练的参数，但是我们不需要在此过程中对他们进行梯度计算。\n",
    "\n",
    "也可以通过将代码块包装在 `with torch.no_grad():` 中，来阻止autograd跟踪设置了 `.requires_grad=True` 的张量的历史记录。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(x.requires_grad)\n",
    "print((x ** 2).requires_grad)\n",
    "\n",
    "with torch.no_grad():\n",
    "    print((x ** 2).requires_grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">后续阅读：\n",
    ">\n",
    ">`autograd`和`Function`的文档见：https://pytorch.org/docs/autograd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (Spyder)",
   "language": "python3",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "214.391px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
